/**
 * 此指令输入密码会判断密码强度，使用时需和input标签绑定同一个数据，即ng-model
 * 需要紧接着
 * created by wenhan
 */
APP.directive('passwordStrength', ['$rootScope', '$state', '$ionicScrollDelegate', '$timeout',
  function ($rootScope, $state, $ionicScrollDelegate, $timeout) {
    return {
      restrict: 'EA',
      replace: true,
      scope: {
        bindData: '=bindData'
      },
      template: '<div style="padding-top: 5px;">' +
      '<div>' +
      '<div style="padding: 5px;width: 15%;display: inline-block;border-right: 1px solid #d9d9d9;" ng-class="level<=1?\'assertive-bg\':\'stable-bg\'"></div>' +
      '<div style="padding: 5px;width: 15%;display: inline-block;border-right: 1px solid #d9d9d9;" ng-class="level>1&&level<4?\'energized-bg\':\'stable-bg\'"></div>' +
      '<div style="padding: 5px;width: 15%;display: inline-block;" ng-class="level==4?\'balanced-bg\':\'stable-bg\'"></div>' +
      '</div>' +
      '<div style="">' +
      '<div style="width: 15%;display: inline-block;text-align: center;">弱</div>' +
      '<div style="width: 15%;display: inline-block;text-align: center;">中</div>' +
      '<div style="width: 15%;display: inline-block;text-align: center;">强</div>' +
      '</div>' +
      '</div>',
      link: function (scope, element, attr) {
        scope.level = 0;
        scope.$watch('bindData',function(newValue,oldValue){
          scope.level = checkStrong();
        });
        var checkStrong = function () {
          if (scope.bindData.length <= 4)
            return 0; //密码太短
          var mode = 0;
          for (i = 0; i < scope.bindData.length; i++) {
            //密码模式
            mode |= charMode(scope.bindData.charCodeAt(i));
          }
          return bitTotal(mode);
        };

        var charMode = function (el) {
          if (el >= 48 && el <= 57) //数字
          {
            return 1;
          }
          if (el >= 65 && el <= 90) //大写
          {
            return 2;
          }
          if (el >= 97 && el <= 122) //小写
          {
            return 4;
          }
          else {
            return 8;
          }
        };

        //bitTotal函数
        //计算密码模式
        var bitTotal = function (num) {
          var mode = 0;
          for (i = 0; i < 4; i++) {
            if (num & 1) {
              mode++;
            }
            num >>>= 1;
          }
          return mode;
        }
      }
    }
  }]);
